﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ganaye.EmbeddedDb
{
    abstract class ModifiedRecords
    {
        internal abstract void Set(uint p, Record record, ref bool isFirst);
        internal abstract void RemoveAndGetNext(uint recordNo, ref uint nextRecordNo, ref Record nextRecord);
    }

    class SlowModifiedRecordsUsingLockAndSortedDictionary : ModifiedRecords
    {
        private SortedDictionary<uint, Record> mDict;
        private object mLock = new object();

        public SlowModifiedRecordsUsingLockAndSortedDictionary()
        {
            mDict = new SortedDictionary<uint, Record>(new UInt32Comparer());
        }

        private class UInt32Comparer : IComparer<uint>
        {
            #region IComparer<uint> Members

            int IComparer<uint>.Compare(uint x, uint y)
            {
                return (int)(x - y);
            }

            #endregion
        }

        internal override void Set(uint p, Record record, ref bool isFirst)
        {
            lock (mLock)
            {
                isFirst = (mDict.Count == 0);
                mDict[p] = record;
            }
        }

        internal override void RemoveAndGetNext(uint recordNo, ref uint nextRecordNo, ref Record nextRecord)
        {
            lock (mLock)
            {
                if (recordNo != uint.MaxValue) mDict.Remove(recordNo);
                using (var enumerator = mDict.GetEnumerator())
                {
                    if (enumerator.MoveNext())
                    {
                        nextRecordNo = enumerator.Current.Key;
                        nextRecord = enumerator.Current.Value;
                    }
                    else
                    {
                        nextRecordNo = uint.MaxValue;
                        nextRecord = null;
                    }
                }
            }
        }
    }
    
    class ModifiedRecordsUsingBTree : ModifiedRecords
    {
        // this is a dream?

        internal override void Set(uint p, Record record, ref bool isFirst)
        {
            throw new NotImplementedException();
        }

        internal override void RemoveAndGetNext(uint recordNo, ref uint nextRecordNo, ref Record nextRecord)
        {
            throw new NotImplementedException();
        }
    }
}
